package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneOfferInstService;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneProdInstService;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDeliveryDTO;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosSceneHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteInstRelDTO;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.enums.RelType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class KitePosDeliveryHandler implements IKitePosSceneHandler {

    @Autowired
    private IOperateSceneOfferInstService operateSceneOfferInstService;

    @Autowired
    private IOperateSceneProdInstService operateSceneProdInstService;

    @Override
    public void handle(KitePosHandlerContext context) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        List<KitePosDeliveryDTO> deliverys = Lists.newArrayList();

        List<Map<String, Object>> deliveryInfos = querySceneInstService.getExtParameterValue(context.getSceneInstId(), "offerInstDeliveryInfos");
        if (!KiteListUtils.isEmpty(deliveryInfos)) {
            deliverys.addAll(packageDeliveries(context.getSceneInstId(), false, deliveryInfos));
        }

        List<Map<String, Object>> deliveryInfosDel = querySceneInstService.getExtParameterValue(context.getSceneInstId(), "offerInstDeliveryInfosDel");
        if (!KiteListUtils.isEmpty(deliveryInfosDel)) {
            deliverys.addAll(packageDeliveries(context.getSceneInstId(), true, deliveryInfosDel));
        }

        context.getPosDto().setDelivery(deliverys);
    }

    private List<KitePosDeliveryDTO> packageDeliveries(String sceneInstId, Boolean isDelete, List<Map<String, Object>> deliveryInfos) {
        List<KitePosDeliveryDTO> deliverys = Lists.newArrayList();
        for (Map<String, Object> delivery : deliveryInfos) {
            if (!isDelete) {
                dealDeliveryAttrOfProdInst(sceneInstId, delivery);
            }

            KitePosDeliveryDTO deliveryDto = new KitePosDeliveryDTO();

            deliveryDto.setInstanceId(delivery.get("instId").toString());

            List<KiteAttr> kiteAttrs = (List<KiteAttr>) delivery.get("kiteAttrs");

            deliveryDto.setIdType("5");
            deliveryDto.setIdNo(getValue(kiteAttrs, "ORD10039"));
            deliveryDto.setChangeType(ChangeTypeUtils.getChangeType(KiteMapUtils.getString(delivery, "actionType")));
            deliveryDto.setProvince(getValue(kiteAttrs, "ORD10053"));
            deliveryDto.setCity(getValue(kiteAttrs, "ORD10054"));
            deliveryDto.setDistrict(getValue(kiteAttrs, "ORD10055"));
            deliveryDto.setAddress(getValue(kiteAttrs, "ORD10040"));
            deliveryDto.setName(getValue(kiteAttrs, "ORD10037"));
            deliveryDto.setPhone(getValue(kiteAttrs, "ORD10038"));
            deliveryDto.setRemark(getValue(kiteAttrs, "ORD10041"));
            deliveryDto.setDestItemId(getValue(kiteAttrs, "extInstId"));

            deliverys.add(deliveryDto);
        }
        return deliverys;
    }

    private String getValue(List<KiteAttr> kiteAttrs, String fieldName) {
        List<KiteAttr> kiteAttr = kiteAttrs.stream().filter(attr -> KiteStringUtils.equals(fieldName, attr.getFieldName())).collect(Collectors.toList());
        if (!KiteListUtils.isEmpty(kiteAttr)) {
            return kiteAttr.get(0).getValue();
        }
        return "";
    }

    /**
     * 处理融合商品的收货信息属性
     * @param sceneInstId
     * @param delivery
     */
    private void dealDeliveryAttrOfProdInst(String sceneInstId, Map<String, Object> delivery) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        String custId = Optional.ofNullable(querySceneInstService.getSceneInst(sceneInstId)).map(KiteSceneInst::getCustId).orElse(null);
        String rootInstId = Optional.ofNullable(querySceneInstService.getSceneInst(sceneInstId)).map(KiteSceneInst::getRootInstId).orElse(null);
        InstType rootInstType = Optional.ofNullable(querySceneInstService.getSceneInst(sceneInstId)).map(KiteSceneInst::getRootInstType).orElse(null);
        if (!KiteStringUtils.isEmpty(rootInstId) && !KiteObjectUtils.isEmpty(rootInstType)) {
            List<KiteAttr> kiteAttrs = (List<KiteAttr>) delivery.get("kiteAttrs");
            // 取收货信息的地址，收货人和联系电话
            String province = getValue(kiteAttrs, "ORD10053");//省
            String city = getValue(kiteAttrs, "ORD10054");//市
            String region = getValue(kiteAttrs, "ORD10055");//区
            String detailAddr = getValue(kiteAttrs, "ORD10040");//详细地址
            StringBuilder addressSb = new StringBuilder();
            addressSb.append(province).append(city).append(region).append(detailAddr);

            String receiverValue = getValue(kiteAttrs, "ORD10037");
            String telphoneValue = getValue(kiteAttrs, "ORD10038");
            String contactEmailValue = getValue(kiteAttrs, "200004113");

            KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, rootInstId);
            List<KiteOfferInst> allOfferInsts = new ArrayList<>();
            List<KiteOfferInst> offerInsts = querySceneInstService.listMainOfferInsts(sceneInstId);
            List<KiteOfferInst> filterOfferInsts = offerInsts.stream().filter(offerinst -> KiteStringUtils
                .equals(getValue(kiteAttrs, "offerName"), offerinst.getOfferInstId())).collect(Collectors.toList());
            //关联商品对应的销售品实例
            for(KiteOfferInst mainOfferInst :filterOfferInsts){
                allOfferInsts.add(mainOfferInst);
                //关联商品对应的销售品实例下附加商品
                List<KiteInstRelDTO> offerInstRels = querySceneInstService.listInstRelsByAInst(custId, InstType.MAIN_OFFER_INST, mainOfferInst.getOfferInstId(), InstType.MAIN_OFFER_INST);
                offerInstRels = offerInstRels.stream().filter(rel -> java.util.Objects.equals(RelType.OFFER_OBJ_REL_TYPE_120000, rel.getRelType())).collect(Collectors.toList());
                for(KiteOfferInst zOfferInst :offerInsts){
                    String offerInstId = zOfferInst.getOfferInstId();
                    for(KiteInstRelDTO relDTO :offerInstRels){
                        String zOfferInstId = relDTO.getzInstId();
                        if(KiteStringUtils.isEqual(offerInstId,zOfferInstId)){
                            allOfferInsts.add(zOfferInst);
                        }
                    }
                }
            }
            if (Objects.equal(rootInstType, InstType.GIFT_OFFER_INST)) {
                //收货类型
                String deliveryType = null;
                List<KiteProdInst> prodInsts = querySceneInstService.listProdInstsFromOfferInst(custId, offerInst.getOfferInstId());
                if (!KiteListUtils.isEmpty(prodInsts)) {
                    deliveryType = prodInsts.get(0).getAttrValue("200004110");
                }
                //组合发货
                if (KiteStringUtils.equals("100007295", deliveryType)) {
                    //融合本身
                    querySceneInstService.listGiftOfferInsts(sceneInstId).forEach(OOfferInst -> {
                        KiteProdInst giftProdInsts = null;
                        if (!KiteListUtils.isEmpty(prodInsts)) {
                             giftProdInsts = prodInsts.get(0);
                        }
                        KiteAttr address = OOfferInst.getAttr("200004111"); //收货地址
                        if (!KiteObjectUtils.isEmpty(address)) {
                            operateSceneOfferInstService.updateOfferInstAttr(sceneInstId, OOfferInst.getOfferInstId(), address.getFieldName(), addressSb.toString(), addressSb.toString(), custId, ContextUtil.getUserId().toString());
                        }
                        if(KiteObjectUtils.isEmpty(address) && !KiteObjectUtils.isEmpty(giftProdInsts)){
                            address = giftProdInsts.getAttr("200004111");
                            if (!KiteObjectUtils.isEmpty(address)) {
                                operateSceneProdInstService.updateProdInstAttr(sceneInstId, giftProdInsts.getProdInstId(), address.getFieldName(), addressSb.toString(),addressSb.toString(), custId, ContextUtil.getUserId().toString(), null);
                            }
                        }
                        KiteAttr receiver = OOfferInst.getAttr("200004112"); //收货人
                        if (!KiteObjectUtils.isEmpty(receiver)) {
                            operateSceneOfferInstService.updateOfferInstAttr(sceneInstId, OOfferInst.getOfferInstId(), receiver.getFieldName(), receiverValue, receiverValue, custId, ContextUtil.getUserId().toString());
                        }
                        if(KiteObjectUtils.isEmpty(receiver) && !KiteObjectUtils.isEmpty(giftProdInsts)){
                            receiver = giftProdInsts.getAttr("200004112");
                            if (!KiteObjectUtils.isEmpty(receiver)) {
                                operateSceneProdInstService.updateProdInstAttr(sceneInstId, giftProdInsts.getProdInstId(), receiver.getFieldName(), receiverValue, receiverValue, custId, ContextUtil.getUserId().toString(), null);
                            }
                        }

                        KiteAttr contactEmail = OOfferInst.getAttr("200004113"); //联系人邮箱
                        if (!KiteObjectUtils.isEmpty(contactEmail)) {
                            operateSceneOfferInstService.updateOfferInstAttr(sceneInstId, OOfferInst.getOfferInstId(), contactEmail.getFieldName(), contactEmailValue, contactEmailValue, custId, ContextUtil.getUserId().toString());
                        }
                        if(KiteObjectUtils.isEmpty(contactEmail) && !KiteObjectUtils.isEmpty(giftProdInsts)){
                            contactEmail = giftProdInsts.getAttr("200004113");
                            if (!KiteObjectUtils.isEmpty(receiver)) {
                                operateSceneProdInstService.updateProdInstAttr(sceneInstId, giftProdInsts.getProdInstId(), contactEmail.getFieldName(), contactEmailValue, contactEmailValue, custId, ContextUtil.getUserId().toString(), null);
                            }
                        }

                        KiteAttr telphone = OOfferInst.getAttr("200002891"); //联系电话
                        if (!KiteObjectUtils.isEmpty(telphone)) {
                            operateSceneOfferInstService.updateOfferInstAttr(sceneInstId, OOfferInst.getOfferInstId(), telphone.getFieldName(), telphoneValue, telphoneValue, custId, ContextUtil.getUserId().toString());
                        }
                        if(KiteObjectUtils.isEmpty(telphone) && !KiteObjectUtils.isEmpty(giftProdInsts)){
                            telphone = giftProdInsts.getAttr("200002891");
                            if (!KiteObjectUtils.isEmpty(telphone)) {
                                operateSceneProdInstService.updateProdInstAttr(sceneInstId, giftProdInsts.getProdInstId(), telphone.getFieldName(), telphoneValue, telphoneValue, custId, ContextUtil.getUserId().toString(), null);
                            }
                        }
                    });
                    //成员商品
                    allOfferInsts.stream().forEach(offerInstt -> {
                            querySceneInstService.listProdInstsFromOfferInst(custId, offerInstt.getOfferInstId())
                                .forEach(prodInstt -> {
                                    KiteAttr address = prodInstt.getAttr("200004111"); // 收货地址
                                    if (!KiteObjectUtils.isEmpty(address)) {
                                        operateSceneProdInstService.updateProdInstAttr(sceneInstId,
                                            prodInstt.getProdInstId(), address.getFieldName(), addressSb.toString(),
                                            addressSb.toString(), custId, ContextUtil.getUserId().toString(), null);
                                    }
                                    KiteAttr receiver = prodInstt.getAttr("200004112"); // 收货人
                                    if (!KiteObjectUtils.isEmpty(receiver)) {
                                        operateSceneProdInstService.updateProdInstAttr(sceneInstId,
                                            prodInstt.getProdInstId(), receiver.getFieldName(), receiverValue,
                                            receiverValue, custId, ContextUtil.getUserId().toString(), null);
                                    }

                                    KiteAttr contactEmail = prodInstt.getAttr("200004113"); // 联系人邮箱
                                    if (!KiteObjectUtils.isEmpty(contactEmail)) {
                                        operateSceneProdInstService
                                            .updateProdInstAttr(sceneInstId, prodInstt.getProdInstId(),
                                                contactEmail.getFieldName(), contactEmailValue, contactEmailValue,
                                                custId, ContextUtil.getUserId().toString(), null);
                                    }

                                    KiteAttr telphone = prodInstt.getAttr("200002891"); // 联系电话
                                    if (!KiteObjectUtils.isEmpty(telphone)) {
                                        operateSceneProdInstService.updateProdInstAttr(sceneInstId,
                                            prodInstt.getProdInstId(), telphone.getFieldName(), telphoneValue,
                                            telphoneValue, custId, ContextUtil.getUserId().toString(), null);
                                    }
                                });
                            ;
                        });
                }
                else {
                    // 融合本身
                    querySceneInstService.listGiftOfferInsts(sceneInstId).forEach(offerInst1 -> {
                        KiteProdInst giftProdInsts = null;
                        if (!KiteListUtils.isEmpty(prodInsts)) {
                            giftProdInsts = prodInsts.get(0);
                        }
                        KiteAttr address = offerInst1.getAttr("200004111"); //收货地址
                        if (!KiteObjectUtils.isEmpty(address)) {
                            operateSceneOfferInstService.updateOfferInstAttr(sceneInstId, offerInst1.getOfferInstId(), address.getFieldName(), addressSb.toString(), addressSb.toString(), custId, ContextUtil.getUserId().toString());
                        }
                        if(KiteObjectUtils.isEmpty(address) && !KiteObjectUtils.isEmpty(giftProdInsts)){
                            address = giftProdInsts.getAttr("200004111");
                            if (!KiteObjectUtils.isEmpty(address)) {
                                operateSceneProdInstService.updateProdInstAttr(sceneInstId, giftProdInsts.getProdInstId(), address.getFieldName(), addressSb.toString(),addressSb.toString(), custId, ContextUtil.getUserId().toString(), null);
                            }
                        }
                        KiteAttr receiver = offerInst1.getAttr("200004112"); //收货人
                        if (!KiteObjectUtils.isEmpty(receiver)) {
                            operateSceneOfferInstService.updateOfferInstAttr(sceneInstId, offerInst1.getOfferInstId(), receiver.getFieldName(), receiverValue, receiverValue, custId, ContextUtil.getUserId().toString());
                        }
                        if(KiteObjectUtils.isEmpty(receiver) && !KiteObjectUtils.isEmpty(giftProdInsts)){
                            receiver = giftProdInsts.getAttr("200004112");
                            if (!KiteObjectUtils.isEmpty(receiver)) {
                                operateSceneProdInstService.updateProdInstAttr(sceneInstId, giftProdInsts.getProdInstId(), receiver.getFieldName(), receiverValue, receiverValue, custId, ContextUtil.getUserId().toString(), null);
                            }
                        }
                        KiteAttr telphone = offerInst1.getAttr("200002891"); //联系电话
                        if (!KiteObjectUtils.isEmpty(telphone)) {
                            operateSceneOfferInstService.updateOfferInstAttr(sceneInstId, offerInst1.getOfferInstId(), telphone.getFieldName(), telphoneValue, telphoneValue, custId, ContextUtil.getUserId().toString());
                        }
                        if(KiteObjectUtils.isEmpty(telphone) && !KiteObjectUtils.isEmpty(giftProdInsts)){
                            telphone = giftProdInsts.getAttr("200002891");
                            if (!KiteObjectUtils.isEmpty(telphone)) {
                                operateSceneProdInstService.updateProdInstAttr(sceneInstId, giftProdInsts.getProdInstId(), telphone.getFieldName(), telphoneValue, telphoneValue, custId, ContextUtil.getUserId().toString(), null);
                            }
                        }

                        KiteAttr contactEmail = offerInst1.getAttr("200004113"); //联系人邮箱
                        if (!KiteObjectUtils.isEmpty(contactEmail)) {
                            operateSceneOfferInstService
                                .updateOfferInstAttr(sceneInstId, offerInst1.getOfferInstId(), telphone.getFieldName(),
                                    contactEmailValue, contactEmailValue, custId, ContextUtil.getUserId().toString());
                        }
                        if (KiteObjectUtils.isEmpty(contactEmail) && !KiteObjectUtils.isEmpty(giftProdInsts)) {
                            contactEmail = giftProdInsts.getAttr("200004113");
                            if (!KiteObjectUtils.isEmpty(contactEmail)) {
                                operateSceneProdInstService
                                    .updateProdInstAttr(sceneInstId, giftProdInsts.getProdInstId(),
                                        contactEmail.getFieldName(), contactEmailValue, contactEmailValue, custId,
                                        ContextUtil.getUserId().toString(), null);
                            }
                        }

                    });
                    // 成员商品
                    allOfferInsts.stream().forEach(offerInst2 -> {
                            querySceneInstService.listProdInstsFromOfferInst(custId, offerInst2.getOfferInstId())
                                .forEach(prodInst2 -> {
                                    KiteAttr address = prodInst2.getAttr("200004111"); // 收货地址
                                    if (!KiteObjectUtils.isEmpty(address)) {
                                        operateSceneProdInstService.updateProdInstAttr(sceneInstId,
                                            prodInst2.getProdInstId(), address.getFieldName(), addressSb.toString(), addressSb.toString(), custId,
                                            ContextUtil.getUserId().toString(), null);
                                    }
                                    KiteAttr receiver = prodInst2.getAttr("200004112"); // 收货人
                                    if (!KiteObjectUtils.isEmpty(receiver)) {
                                        operateSceneProdInstService.updateProdInstAttr(sceneInstId,
                                            prodInst2.getProdInstId(), receiver.getFieldName(), receiverValue, receiverValue, custId,
                                            ContextUtil.getUserId().toString(), null);
                                    }
                                    KiteAttr telphone = prodInst2.getAttr("200002891"); // 联系电话
                                    if (!KiteObjectUtils.isEmpty(telphone)) {
                                        operateSceneProdInstService.updateProdInstAttr(sceneInstId,
                                            prodInst2.getProdInstId(), telphone.getFieldName(), telphoneValue, telphoneValue, custId,
                                            ContextUtil.getUserId().toString(), null);
                                    }

                                    KiteAttr contactEmail = prodInst2.getAttr("200004113"); // 联系人邮箱
                                    if (!KiteObjectUtils.isEmpty(contactEmail)) {
                                        operateSceneProdInstService.updateProdInstAttr(sceneInstId,
                                            prodInst2.getProdInstId(), receiver.getFieldName(), contactEmailValue, contactEmailValue, custId,
                                            ContextUtil.getUserId().toString(), null);
                                    }
                                });
                        });
                }
            }
        }
    }
}
